﻿@using IOA.MES.DataAccess.VModel
@{
    ViewBag.Title = "统一打包";
    Layout = "~/Views/Shared/_LayoutPage.cshtml";

    var actualName = ViewBag.ActualName as string;
    var workshops = ViewBag.WorkShops as List<VWorkshop>;
}

@section Contents{
    <style>
        iframe {
            width: 100%;
            height: 100%;
            border-width: 0px;
        }

        .layui-tab-content {
            padding: 0;
        }

        .layui-tab-item {
            width: 100%;
            height: calc(100vh - 240px);
        }

        .layui-form-item .layui-form-checkbox[lay-skin=primary] {
            margin-top: 0;
            margin-left: 20px;
        }
    </style>
}

<div id="page"></div>

<script type="text/template" id="tplPage">
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-form layui-card-header layuiadmin-card-header-auto">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">{{lang.Field.Operator}}：</label>
                        <div class="layui-input-inline">
                            <input type="text" value="@actualName" disabled class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">{{lang.Field.WorkShop}}：</label>
                        <div class="layui-input-inline">
                            <select id="selWorkshops" lay-filter="selWorkshops">
                                @foreach (var item in workshops)
                                {
                                    <option value="@item.WorkshopCode">@item.WorkshopName</option>
                                }
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button id="btnLock" class="layui-btn layuiadmin-btn-list" type="button">锁定</button>
                        <input id="cbPrintMark" type="checkbox" title="打印唛头" lay-skin="primary" checked />
                        <input id="cbPrintLabel" type="checkbox" title="打印边框条码" lay-skin="primary" checked />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">{{lang.Field.ScanCode}}：</label>
                    <div class="layui-input-block">
                        <input id="txtBarCode" type="text" placeholder="扫描组件条码" class="layui-input" disabled>
                        <audio id="audio" autoplay style="display:none;"></audio>
                    </div>
                </div>
            </div>
        </div>

        <div class="layui-card">
            <div class="layui-card-body">
                <div class="layui-tab" lay-filter="pack_tabs">
                    <ul class="layui-tab-title" id="tabHeaders">
                    </ul>
                    <div class="layui-tab-content" id="tabContents">
                    </div>
                </div>
            </div>
        </div>
    </div>
</script>

@section Scripts{
    <script>
        var curWorkshopCode = "";
        var vm = new Vue({
            el: "#page",
            template: "#tplPage",
            data: {
                lang: JSON.parse(lang).package
            }
        });

        setTimeout(function () {
            initLayui();
        }, 50);
        function initLayui() {
            layui.use(['element', 'layer', 'form', 'laydate'], function () {
                var layer = layui.layer,
                    element = layui.element,
                    form = layui.form;
                form.render();

                $(document).on("click", "#btnLock", function () {
                    if ($("#selWorkshops").attr("disabled")) {
                        $("#selWorkshops").removeAttr("disabled");
                        $(this).text("锁定");
                        $("#txtBarCode").attr("disabled", "disabled");
                    } else {
                        var workshopCode = $("#selWorkshops").val().trim();
                        if (!workshopCode) {
                            layer.msg("请选择打包车间", { icon: 5 });
                        }
                        curWorkshopCode = workshopCode;
                        $("#selWorkshops").attr("disabled", "disabled");
                        $("#txtBarCode").removeAttr("disabled");
                        $(this).text("更换车间");
                        $("#txtBarCode").focus();

                        queryPacks();
                    }
                    $(this).toggleClass("layui-btn-danger");
                    form.render();
                });

                function queryPacks() {
                    var loadId = layer.load();
                    $.ajax({
                        url: "/WorkOrder/QueryUnFinishedPacks",
                        data: {
                            workshopCode: curWorkshopCode
                        },
                        complete: function () {
                            layer.close(loadId);
                        },
                        success: function (res) {
                            if (res.ErrCode != 200) {
                                layer.msg(res.ErrMsg, { icon: 5 });
                                return;
                            }

                            renderPacks(res.Data);
                        }
                    });
                }

                function renderPacks(packs) {
                    var headers = new Array(),
                        contents = new Array();
                    for (var i = 0; i < packs.length; i++) {
                        headers.push('<li class="' + (i <= 0 ? 'layui-this' : '') + '" index="' + packs[i].PackIndex + '">【' + packs[i].PackIndex + '】' + packs[i].PackNo + '</li>');
                        contents.push('<div class="layui-tab-item'
                            + (i <= 0 ? ' layui-show' : '')
                            + '" index="' + packs[i].PackIndex + '"><iframe src="/WorkOrder/Packing?workshopCode=' + curWorkshopCode
                            + '&packNo=' + packs[i].PackNo + '" /></div>');
                    }
                    $("#tabHeaders").html(headers.join(""));
                    $("#tabContents").html(contents.join(""));

                    element.init();
                }

                $("#txtBarCode").keyup(function (e) {
                    if (e.keyCode != 13) {
                        return;
                    }

                    packProduct($(this).val().trim().toUpperCase())
                    $(this).val("");
                    $(this).focus();
                });

                function packProduct(code) {
                    var loadId = layer.load();
                    $.ajax({
                        url: "/WorkOrder/PackProduct",
                        data: {
                            workshopCode: curWorkshopCode,
                            barCode: code
                        },
                        complete: function () {
                            layer.close(loadId);
                        },
                        error: function () {
                            playAudio("error");
                        },
                        success: function (res) {
                            if (res.ErrCode != 200) {
                                return layer.open({
                                    type: 1
                                    , content: '<div style="padding: 20px;">' + res.ErrMsg + '</div>'
                                    , btn: '确定'
                                    , btnAlign: 'c' //按钮居中
                                });
                            }
                            var pack = res.Data;
                            if (pack.PackNo === '') {
                                addNewPack(pack.PackIndex, code);
                            } else if (pack.PackStatus === 1) {
                                finishPack(pack.PackIndex, pack.PackNo)
                            } else {
                                pushCode2Pack(pack, code);
                            }
                        }
                    });
                }

                var lastPackNo = "";
                //添加新包装
                function addNewPack(packIndex, code) {
                    playAudio('new_pack');

                    var header = '<li class="layui-this" index="' + packIndex + '">【' + packIndex + '】新建包装</li>';
                    var content = '<div class="layui-tab-item layui-show" index="' + packIndex
                        + '"><iframe src="/WorkOrder/Packing?workshopCode=' + curWorkshopCode
                        + '&isNewPack=true&packNo=' + lastPackNo + '&barCode=' + code + '" /></div>';

                    var tabAdded = false;
                    var headers = $("#tabHeaders li");
                    var contents = $("#tabContents .layui-tab-item");
                    for (var i = 0; i < headers.length; i++) {
                        $(headers[i]).removeClass("layui-this");
                        $(contents[i]).removeClass("layui-show");

                        if (packIndex + 1 === parseInt($(headers[i]).attr('index'))) {
                            $(headers[i]).before(header);
                            $(contents[i]).before(content);
                            tabAdded = true;
                            break;
                        }
                    }
                    if (!tabAdded) {
                        $("#tabHeaders").append(header);
                        $("#tabContents").append(content);
                    }
                    element.init();
                }

                //添加条码到包装
                function pushCode2Pack(pack, code) {
                    var headers = $("#tabHeaders li");
                    var contents = $("#tabContents .layui-tab-item");

                    for (var i = 0; i < headers.length; i++) {
                        var header = $(headers[i]),
                            content = $(contents[i]);
                        if (pack.PackIndex === parseInt(header.attr("index"))) {
                            header.addClass("layui-this");
                            content.addClass("layui-show");

                            var frame = content.find("iframe")[0];
                            frame.contentWindow.postMessage({ type: 'pushCode', data: code }, '*');
                        } else {
                            header.removeClass("layui-this");
                            content.removeClass("layui-show");
                        }
                    }
                    element.init();

                    playStack(pack.PackIndex, pack.Quantity);
                }

                //完成包装 || 解包
                function finishPack(packIndex, packNo, unPack) {
                    var headers = $("#tabHeaders li");
                    var contents = $("#tabContents .layui-tab-item");

                    for (var i = 0; i < headers.length; i++) {
                        var header = $(headers[i]),
                            content = $(contents[i]);
                        if (packIndex === parseInt(header.attr("index"))) {
                            header.remove();
                            content.remove();
                        }
                    }

                    headers = $("#tabHeaders li");
                    contents = $("#tabContents .layui-tab-item");
                    for (var i = 0; i < headers.length; i++) {
                        var header = $(headers[i]),
                            content = $(contents[i]);
                        if (i <= 0) {
                            header.addClass("layui-this");
                            content.addClass("layui-show");
                        } else {
                            header.removeClass("layui-this");
                            content.removeClass("layui-show");
                        }
                    }
                    element.init();

                    if (!unPack) {
                        //不是解包
                        playFinish(packIndex);
                        lastPackNo = packNo;

                        var markChecked = $("#cbPrintMark")[0].checked,
                            borderLabelChecked = $("#cbPrintLabel")[0].checked;
                        if (markChecked && !borderLabelChecked) {
                            printMark(packNo, 0);
                        } else if (!markChecked && borderLabelChecked) {
                            printMark(packNo, 1);
                        } else if (markChecked && borderLabelChecked) {
                            printMark(packNo, 2);
                        }
                    }
                }

                //打印唛头和边框
                function printMark(packNo, printType) {
                    if (!window.parent.getConnectionStatus()) {
                        window.parent.layui.layer.open({
                            type: 1,
                            content: '<div style="padding: 50px;">本地工具已断开，无法执行打印任务，请打开本地“MES本地工具”</div>',
                        });
                        return;
                    }
                    var message = printType == 0 ? "后台正在生成唛头清单，成功后将自动打开"
                        : (printType == 1 ? "后台正在打印边框条码" : "后台正在生成唛头清单并打印条码，成功后将自动打开");
                    window.parent.layui.layer.open({
                        type: 1,
                        content: '<div style="padding: 50px;">' + message + '，请稍后...</div>',
                    });

                    window.parent.parent.sendMessage(JSON.stringify({
                        Command: "PrintPack",
                        Body: {
                            PackNo: packNo,
                            PrintType: printType
                        }
                    }));
                }

                //监听子页面消息
                window.addEventListener('message', (res) => {
                    console.log(res);
                    var data = res.data.data;
                    if (res.data.type === 'new_pack') {
                        var headers = $("#tabHeaders li");
                        var contents = $("#tabContents .layui-tab-item");

                        for (var i = 0; i < headers.length; i++) {
                            var header = $(headers[i]),
                                content = $(contents[i]);
                            if (data.pack.PackIndex === parseInt(header.attr("index"))) {
                                header.text('【' + data.pack.PackIndex + '】' + data.pack.PackNo)
                                content.html('<iframe src="/WorkOrder/Packing?workshopCode=' + curWorkshopCode
                                    + '&packNo=' + data.pack.PackNo + '" />');
                            }
                        }
                        element.init();

                        packProduct(data.barCode);
                    } else if (res.data.type === 'finish_pack') {
                        finishPack(data.packIndex, data.packNo)
                    } else if (res.data.type === 'un_pack') {
                        finishPack(data.packIndex, data.PackNo, true)
                    }

                    $("#txtBarCode").focus();
                }, false);

                var audioArray = new Array(),
                    mediaIndex = 0,
                    audio = document.getElementById("audio");
                audio.addEventListener('ended', function () {
                    if (mediaIndex < audioArray.length - 1) {
                        mediaIndex++;
                        audio.src = "/res/audio/" + audioArray[mediaIndex] + ".mp3";
                        audio.play();
                    }
                }, false);
                //开始从0播放
                function startPlay() {
                    mediaIndex = 0;
                    audio.src = "/res/audio/" + audioArray[0] + ".mp3";
                    audio.play();
                }
                //播放一般提示
                function playAudio(type) {
                    audioArray = [type];
                    startPlay();
                }
                //播放一般提示
                function playFinish(index) {
                    var array = ["no"];
                    array = array.concat(getNumAudios(index));
                    array.push("pack");
                    array.push("pack_finish");

                    audioArray = array;
                    startPlay();
                }
                //播放堆栈提示
                function playStack(index, block) {
                    var array = ["no"];
                    array = array.concat(getNumAudios(index));
                    array.push("pack");
                    array.push("no");
                    array = array.concat(getNumAudios(block));
                    array.push("block");

                    audioArray = array;
                    startPlay();
                }
                function getNumAudios(num) {
                    var array = new Array();
                    if (num <= 10) {
                        array.push(num + '');
                    } else if (num < 20) {
                        array.push(10 + '');
                        array.push(num % 10 + '');
                    } else {
                        array.push(parseInt(num / 10) + '');
                        array.push(10 + '');
                        if (num % 10 > 0) {
                            array.push(num % 10 + '');
                        }
                    }
                    return array;
                }
            });
        }
    </script>
}
